﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace NDK.Utils
{
    public partial class DataGridViewUtils
    {
        /// <summary>
        /// 处理剪贴板中的内容,复制到DataGridView
        /// </summary>
        /// <param name="dataGridView1"></param>
        public static void PasteData(DataGridView dataGridView1)
        {
            try
            {
                string clipboardText = Clipboard.GetText(); //获取剪贴板中的内容
                if (string.IsNullOrEmpty(clipboardText))
                {
                    return;
                }
                int colnum = 0;
                int rownum = 0;

                //start wps 表格复制到 datagridview
                string[] lines = clipboardText.Split(new char[] { '\n' });

                if (lines.Length > 0)
                {
                    rownum = lines.Length - 1;
                    string[] cols = lines[0].Trim().Split('\t');
                    colnum = cols.Length;
                }


                //for (int i = 0; i < clipboardText.Length; i++)
                //{
                //    if (clipboardText.Substring(i, 1) == "\t")
                //    {
                //        colnum++;
                //    }
                //    if (clipboardText.Substring(i, 1) == "\n")
                //    {
                //        rownum++;
                //    }
                //}

                if (colnum == 0 || rownum == 0)
                {
                    return;
                }
                //colnum = colnum / rownum + 1;


                int selectedRowIndex, selectedColIndex;
                selectedRowIndex = dataGridView1.CurrentRow.Index;
                selectedColIndex = dataGridView1.CurrentCell.ColumnIndex;
                if (selectedRowIndex + rownum > dataGridView1.RowCount || selectedColIndex + colnum > dataGridView1.ColumnCount)
                {
                    MessageBox.Show("粘贴区域大小不一致");
                    return;
                }
                String[][] temp = new String[rownum][];
                for (int i = 0; i < rownum; i++)
                {
                    temp[i] = new String[colnum];
                }
                int m = 0, n = 0, len = 0;
                while (len != clipboardText.Length)
                {
                    String str = clipboardText.Substring(len, 1);
                    if (str == "\t")
                    {
                        n++;
                    }
                    else if (str == "\n")
                    {
                        m++;
                        n = 0;
                    }
                    else
                    {
                        temp[m][n] += str.Trim(new char[] { '\r', '\n', '\t' }).Trim();
                    }
                    len++;
                }
                for (int i = selectedRowIndex; i < selectedRowIndex + rownum; i++)
                {
                    for (int j = selectedColIndex; j < selectedColIndex + colnum; j++)
                    {
                        dataGridView1.Rows[i].Cells[j].Value = temp[i - selectedRowIndex][j - selectedColIndex];
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        #region 得到某列的所有值
        /// <summary>
        /// 得到某列的所有值
        /// </summary>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public static List<string> GetDataGridViewColumnValue(DataGridView dgv, int columnIndex)
        {
            List<string> ls = new List<string>();
            string cellValue;
            try
            {
                for (int i = 0; i < dgv.Rows.Count - 0; i++)
                {
                    if (!dgv.Rows[i].IsNewRow)
                    {
                        cellValue = dgv.Rows[i].Cells[columnIndex].Value.ToString();
                        ls.Add(cellValue);
                    }
                }
            }
            catch (System.Exception ex)
            {
                return ls;
            }
            return ls;
        }
        #endregion

        #region 得到某行的所有值
        /// <summary>
        /// 得到某行的所有值
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static List<string> GetDataGridViewRowValue(DataGridView dgv, int rowIndex)
        {
            List<string> ls = new List<string>();

            for (int i = 0; i < dgv.ColumnCount; i++)
            {
                string cellValue = dgv.Rows[rowIndex].Cells[i].Value.ToString();
                ls.Add(cellValue);
            }
            return ls;
        }
        #endregion

        #region 获得DataGridView当前选中行的数据
        /// <summary>
        /// 获得DataGridView当前选中行的数据
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>返回List</returns>
        public static List<string> GetDataGridViewCurrentValues(DataGridView dgv)
        {
            try
            {
                List<string> list = new List<string>();


                //object shiyan=  dgv.CurrentRow.Cells[0].Value;

                int cnt = dgv.CurrentRow.Cells.Count;
                if (cnt == 0)
                    return null;
                string cell = null;
                for (int i = 0; i < cnt; i++)
                {
                    if (dgv.CurrentRow.Cells[i].Value != null)
                    {
                        cell = dgv.CurrentRow.Cells[i].Value.ToString();
                        list.Add(cell);
                    }

                }
                return list;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        #endregion


        public static void SetDataGridViewCurrentRowCellValue(DataGridView dgv, string columnIndex, string value)
        {
            if (dgv != null && dgv.CurrentRow != null)
            {
                dgv.CurrentRow.Cells[columnIndex].Value = value;
            }
        }


        #region 获得DataGridView当前选中行，指定列的cell值
        /// <summary>
        /// 获得DataGridView当前选中行，指定列的cell值
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="columnIndex"></param>
        /// <returns></returns>
        public static string GetDataGridViewCurrentRowCellValue(DataGridView dgv, int columnIndex)
        {
            string cell = "";
            if (dgv != null && dgv.CurrentRow != null)
            {
                cell = dgv.CurrentRow.Cells[columnIndex].Value.ToString();
            }
            return cell;
        }
        public static string GetDataGridViewCurrentRowCellValue(DataGridView dgv, string columnName)
        {
            string cell = "";
            if (dgv != null && dgv.CurrentRow != null)
            {
                cell = dgv.CurrentRow.Cells[columnName].Value.ToString();
            }
            return cell;
        }
        #endregion



        public static void DeleteSelectedRows(DataGridView dgv)
        {
            try
            {
                //选中的行数
                int iCount = dgv.SelectedRows.Count;
                if (iCount < 1)
                {
                    return;
                }
                for (int i = 0; i < dgv.Rows.Count - 1; i++)
                {
                    if (true == dgv.Rows[i].Selected)
                        dgv.Rows.RemoveAt(i);
                }
                //删除任意行数据后，应该刷新dataGridView表格，使索引值从上至下按大小顺序排序
                for (int i = 0; i < dgv.Rows.Count - 1; i++)
                {
                    dgv.Rows[i].Cells[0].Value = i + 1;
                }
            }
            catch (Exception ex)
            {

            }
        }
        #region 获得DataGridView,指定列的cell值
        /// <summary>
        /// 获得DataGridView指定行列的cell值
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="columnIndex"></param>
        /// <returns></returns>
        public static string GetDataGridViewCellValue(DataGridView dgv, int rowIndex, int columnIndex)
        {
            string cell = dgv.Rows[rowIndex].Cells[columnIndex].Value.ToString();
            return cell;
        }
        #endregion

        /// <summary>
        /// 将指定DataGridView转换成DataTable，带表头（注意：DataGridView必须有列名称）
        /// </summary>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public static DataTable DataGridViewToDataTable(DataGridView dgv)
        {
            DataTable dataTable = new DataTable();
            //列强制转换
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                string columnName = column.Name.ToString();
                if (string.IsNullOrEmpty( columnName))
                {
                    return null;
                }
                DataColumn dc = new DataColumn(columnName);
                
                dataTable.Columns.Add(dc);
            }

            foreach (DataGridViewRow row in dgv.Rows)
            {
                DataRow dr = dataTable.NewRow();
                foreach (DataGridViewColumn c in dgv.Columns)
                {
                    dr[c.Name] = Convert.ToString(row.Cells[c.Name].Value);
                }
                dataTable.Rows.Add(dr);
            }
            return dataTable;
        }

        /// <summary>
        /// 将指定DataGridView的选中行转换成DataTable，带表头（注意：DataGridView必须有列名称）
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="selectedRows"></param>
        /// <returns></returns>
        public static DataTable DataGridViewToDataTable(DataGridView dgv, DataGridViewSelectedRowCollection selectedRows)
        {
            DataTable dataTable = new DataTable();
            //列强制转换
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                string columnName = column.Name.ToString();
                if (string.IsNullOrEmpty( columnName))
                {
                    return null;
                }
                DataColumn dc = new DataColumn(columnName);
                
                dataTable.Columns.Add(dc);
            }

            foreach (DataGridViewRow row in selectedRows)
            {
                DataRow dr = dataTable.NewRow();
                foreach (DataGridViewColumn c in dgv.Columns)
                {
                    dr[c.Name] = Convert.ToString(row.Cells[c.Name].Value);
                }
                dataTable.Rows.Add(dr);
            }
            return dataTable;
        }
    }
}
